package emby.lang;

import java.io.Serializable;

import emby.ASTNode;
import emby.EmbyRuntime;
import emby.stmt.Return;
import emby.stmt.Statement;
import emby.writer.IEmbyCodifier;

/**
 * A block represents an array of AST nodes, with special handling in the eval method
 * @author Justin
 *
 */
public class Block extends ASTNode implements Serializable{

	private static final long serialVersionUID = -8928860692582831982L;
	ASTNode[] operations;
	public Block( ASTNode... ops){
		operations = ops;
	}

	/**
	 * Block's
	 * Always returns null UNLESS there was a return statement in the block.
	 */
	@Override
	public Object eval(Scope s) {
		//Scope oldScope = Scope.current;
		//Scope.current = s;
		if(EmbyRuntime.echo){

			emby.util.Print.println("Evaluating block: ",operations);
			emby.util.Print.tab();
		}

		for( int i =0; i<operations.length; i++){
			//System.out.println("0Return detected?");
			if(operations[i] instanceof Return){
				//System.out.println("Return detected!");
				//Scope.current = oldScope;
				Object o = operations[i].eval(s);
				if(EmbyRuntime.echo){
					emby.util.Print.untab();
				}
				return o;
			}

			else if(operations[i] instanceof Statement){
				Object o = operations[i].eval(s);
				if( o!=null){ // if a statement returns something, that means there was a return statement within that statement.
					//Scope.current = oldScope;
					if(EmbyRuntime.echo){
						emby.util.Print.untab();
					}
					return o;
				}
			}
			else{
				operations[i].eval(s);
			}
			//System.out.println("No Return detected");
		}

		//Scope.current = oldScope;
		if(EmbyRuntime.echo){
			emby.util.Print.untab();
		}
		return null;
	}

	public void add(ASTNode operation){
		 ASTNode[] newOps = new ASTNode[operations.length+1];
		for(int i = 0; i< operations.length;i++){newOps[i]=operations[i];};
		newOps[newOps.length-1]=operation;
		operations = newOps;
	}
	
	public void codify(IEmbyCodifier ec){
		ec.block(operations);
	}
}
